package config

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/BurntSushi/toml"
	"go.uber.org/zap"
)

type Config struct {
	Es      EsConf      `json:"es" toml:"es"`
	Cluster ClusterConf `json:"cluster" toml:"cluster"`
	Logger  LoggerConf  `json:"logger" toml:"logger"`
}

type EsConf struct {
	Host     string `json:"host" toml:"host"`
	Port     string `json:"port" toml:"port"`
	Username string `json:"username" toml:"username"`
	Password string `json:"password" toml:"password"`
	Index    string `json:"index" toml:"index"`
}

type ClusterConf struct {
	Name string `json:"name" toml:"name"`
	Kube string `json:"kube" toml:"kube"`
}

type LoggerConf struct {
	Env    string `json:"env" toml:"env"`
	Level  string `json:"level" toml:"level"`
	Output string `json:"output" toml:"output"`
}

func (c *Config) String() string {
	b, _ := json.Marshal(c)
	return string(b)
}

var C = &Config{}

func (e *EsConf) GetEsDsn() string {
	return fmt.Sprintf("http://%s:%s", e.Host, e.Port)
}

func LoadConfigFromToml(cfgFile string) error {
	if cfgFile == "" {
		return errors.New("需指定配置文件")
	} else {
		if _, err := toml.DecodeFile(cfgFile, C); err != nil {
			return err
		}
	}
	zapLevel := zap.NewAtomicLevel()
	if err := zapLevel.UnmarshalText([]byte(C.Logger.Level)); err != nil {
		panic(err.Error())
	}
	var zapConf zap.Config

	if env := C.Logger.Env; env == "dev" {
		zapConf = zap.NewDevelopmentConfig()
	} else {
		zapConf = zap.NewProductionConfig()
	}
	zapConf.Level = zapLevel

	if C.Logger.Output != "" {
		zapConf.OutputPaths = []string{C.Logger.Output}
		zapConf.ErrorOutputPaths = []string{C.Logger.Output}
	}
	if logger, err := zapConf.Build(); err != nil {
		panic(err.Error())
	} else {
		zap.RedirectStdLog(logger)
		zap.ReplaceGlobals(logger)
	}
	zap.L().Info(fmt.Sprintf("load config: %s", cfgFile))
	return nil
}
